package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"order/models"
)

type OrderController struct {
	beego.Controller
}
type JsonData struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *OrderController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price", 64)
	cate := c.GetString("cate")
	order := models.Order{
		Name:  name,
		Price: price,
		Cate:  cate,
	}
	err := models.DB.Create(&order).Error
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonData{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *OrderController) Upload() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 5)
	orders, total, err := models.OrderUpload(page, pageSize)
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "提交失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		PageData := make(map[string]interface{})
		PageData["orders"] = orders
		PageData["total"] = total
		c.Data["json"] = JsonData{
			Code: 200,
			Msg:  "查询成功",
			Data: PageData,
		}
		c.ServeJSON()
	}

}

func (c *OrderController) Del() {
	id, _ := c.GetInt("id")
	order := models.Order{Id: id}
	err := models.DB.Delete(&order).Error
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonData{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
